import json

from django.db import models

# Create your models here.
from cases.models import Case, TeSuite, Steps
from envs.models import BaseModel, DbInfo


class SuitReport(BaseModel):
    test_suit = models.ForeignKey(TeSuite, verbose_name='案例集', on_delete=models.CASCADE)
    start_time = models.DateTimeField(max_length=60, verbose_name="案例集开始时间")
    end_time = models.DateTimeField(max_length=60, verbose_name="案例集结束时间",blank=True,null=True)
    pass_count = models.IntegerField(verbose_name="通过数量", default=0)
    fail_count = models.IntegerField(verbose_name="失败数量", default=0)
    skip_count = models.IntegerField(verbose_name="忽略的数量", default=0)
    # case_results = models.ManyToManyField(CaseResult, verbose_name="案例结果", help_text="测试案例结果", blank=True)
    take_time = models.IntegerField(blank=True,verbose_name="案例集运行耗时(秒)",null=True)
    total_count = models.IntegerField(blank=True, verbose_name="案例总数", default=0)
    pass_rate = models.FloatField(blank=True, verbose_name="通过率",default=0)
    json_result = models.TextField(verbose_name="json格式报告", blank=True)
    html_result = models.TextField(verbose_name="html格式报告", blank=True)

    class Meta:
        db_table = 'test_suit_report'
        verbose_name = '测试报告'
        verbose_name_plural = '测试报告'

    def __str__(self):
        return self.test_suit.suit_name

    def save(self, *args, **kwargs):
        if self.pass_count or self.fail_count or self.end_time:
            self.total_count = self.pass_count + self.fail_count + self.skip_count
            self.pass_rate = self.pass_count / (self.pass_count + self.fail_count + self.skip_count)
            self.take_time = (self.end_time - self.start_time).seconds
        super().save(*args, **kwargs)

    def get_dict(self):
        return {'test_suit_name':self.test_suit.suit_name,
                'start_time':self.start_time,'end_time':self.end_time,
                'pass_count':self.pass_count,'fail_count':self.fail_count,
                'take_time': self.take_time, 'total_count': self.total_count,'pass_rate': self.pass_rate}



class CaseResult(BaseModel):
    RUN_CHOICES = (
        ('pass', '通过'),
        ('fail', '失败'),
        ('erro', '异常'),
    )
    test_case = models.ForeignKey(Case, verbose_name='案例', on_delete=models.DO_NOTHING)
    case_result_suit = models.ForeignKey(SuitReport,models.SET_NULL,blank=True,null=True,verbose_name="所属案例集")
    start_time = models.DateTimeField(max_length=60, verbose_name="案例开始时间")
    end_time = models.DateTimeField(max_length=60, verbose_name="案例结束时间")
    log_text = models.TextField(verbose_name="日志信息")
    result_status = models.CharField(max_length=60, choices=RUN_CHOICES, verbose_name="运行结果")
    take_time = models.IntegerField(blank=True,verbose_name="案例运行耗时")

    class Meta:
        db_table = 'case_result'
        verbose_name = '案例结果'
        verbose_name_plural = '案例结果'

    def __str__(self):
        return self.test_case.case_name


    def save(self, *args, **kwargs):
        # self.take_time = (self.end_time - self.start_time).seconds
        self.take_time = (self.end_time - self.start_time).microseconds
        super().save(*args, **kwargs)

    def get_dict(self):
        return {'test_case_name':self.test_case.case_name,
                'start_time':self.start_time,'end_time':self.end_time,
                'result_status':self.result_status,
                'take_time': self.take_time, 'log_text': self.log_text}


class StepResult(BaseModel):
    RUN_CHOICES = (
        ('pass', '通过'),
        ('fail', '失败'),
        ('erro', '异常'),
    )

    METHOD_CHOICES = (('GET', 'GET'), ('POST', 'POST'), ('PUT', 'PUT'), ('DELETE', 'DELETE'), ('PATCH', 'PATCH'))
    OPERATION_CHOICES = (('db', '数据库'), ('http', 'http请求'))
    TYPE_CHOICES = (
        ('DQL', '查询'),
        ('DML', '修改/更新/删除'),
    )
    case_result = models.ForeignKey(CaseResult, models.SET_NULL, blank=True, null=True, verbose_name="所属用例")
    test_step = models.ForeignKey(Steps, on_delete=models.DO_NOTHING, verbose_name='步骤')
    url = models.CharField(verbose_name="URL地址", max_length=800, help_text="URL地址", blank=True)
    step_description = models.CharField(max_length=150, verbose_name="步骤描述")
    operation_type = models.CharField(max_length=10, choices=OPERATION_CHOICES, verbose_name="操作类型", )
    method = models.CharField(max_length=20, choices=METHOD_CHOICES, verbose_name="请求方法", blank=True)
    request_header = models.TextField(verbose_name="请求头", blank=True)
    request_body = models.TextField(verbose_name="请求体", blank=True)
    assert_result = models.TextField(verbose_name="预期结果", blank=True)
    response_header = models.TextField(verbose_name="返回头", blank=True,editable=False)
    response_body = models.TextField(verbose_name="返回体", blank=True,editable=False)
    # db_Info = models.ForeignKey(DbInfo, null=True,on_delete=models.DO_NOTHING, verbose_name="数据库", help_text="数据库", blank=True)
    db_info = models.ForeignKey(DbInfo, models.SET_NULL, null=True, verbose_name="数据库", help_text="数据库", blank=True)
    sql_content = models.CharField(max_length=150, verbose_name="SQL内容", blank=True,editable=False)
    sql_type = models.CharField(choices=TYPE_CHOICES, max_length=200, verbose_name="脚本类型", default='DQL',
                              blank=True,editable=False)
    log_text = models.TextField(verbose_name="日志信息")
    result_status = models.CharField(max_length=60, choices=RUN_CHOICES, verbose_name="运行结果")

    class Meta:
        db_table = 'step_result'
        verbose_name = '步骤结果'
        verbose_name_plural = '步骤结果'

    def __str__(self):
        return self.step_description









class Report:
    def __init__(self,suitReport:SuitReport,caseResults:[]):
        self.suitReport=suitReport
        self.caseResults=caseResults
    def get_report_json(self):
        return json.dumps(self.__dict__)
